# coding=utf-8
from django.core.files import uploadedfile
import base64
import io
from django.utils import timezone


def convert_base64(data, name):
    # data:image/jpeg;base64,.....
    meta, sep, binary = data.partition(';base64,')
    if not sep:
        return None
    binary = base64.b64decode(binary.encode('ascii'))
    content_type = meta.lstrip('data:')
    mime_type, sep, extension = content_type.partition('/')

    return uploadedfile.InMemoryUploadedFile(
        io.BytesIO(binary),
        name,
        timezone.now().strftime('%Y-%m-%d_%H%M%S_%f') + '.' + extension,
        content_type, len(binary), None, {}
    )
